﻿#include "musicslider.h"
#include "ui_musicslider.h"

#include <QMouseEvent>
#include <QDebug>

MusicSlider::MusicSlider(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicSlider)
{
    ui->setupUi(this);

    currentPos = 0;
    maxWidth = this->width();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::moveSlider()
{
    ui->outLine->setGeometry(ui->outLine->x(), ui->outLine->y(), currentPos, ui->outLine->height());
}

void MusicSlider::setStep(float ration)
{
    currentPos = maxWidth * ration;
    moveSlider();
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSlider();
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    (void)event;
//    currentPos = event->pos().x();
//    moveSlider();
    // 发送进度条的比率
    emit setMusicSliderPosition(currentPos / (float)maxWidth);
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    // 注意:鼠标移动的时候, 必须在该窗口才会支持拖拽功能
    // 获取当前窗口的范围, 利用QRect::contains()函数来检测是否在这个窗口内部
    QRect musicSliderRect = QRect(0, 0, geometry().width(), geometry().height());
    if(!musicSliderRect.contains(event->pos()))
    {
//       qDebug()<<musicSliderRect<<"-"<<event->pos();
       return;
    }
    // 左键
    if(event->buttons() == Qt::LeftButton)
    {
        currentPos = event->pos().x();
        if(currentPos < 0)
        {
            currentPos = 0;
        }
        if(currentPos > maxWidth)
        {
            currentPos = maxWidth;
        }
        moveSlider();
    }
}
